package com.arcaneshift.model.validators.user;

import com.arcaneshift.manager.action.user.UserManager;
import com.arcaneshift.model.request.user.AddUserRequest;
import com.arcaneshift.security.errors.CredentialsError;
import com.arcaneshift.security.errors.UserError;
import com.common.model.abstracts.AbstractRequest;
import com.common.model.abstracts.AbstractValidator;
import com.common.security.abstracts.AbstractError;
import com.common.security.errors.SessionError;
import com.common.security.exceptions.ManagerException;

public class UsernameUnicityValidator extends AbstractValidator {

	@Override
	public boolean validate(AbstractRequest abstractRequest) {
		AddUserRequest request = null;
		
		if (abstractRequest instanceof AddUserRequest) {
			request = (AddUserRequest) abstractRequest;
		} else {
			error = new SessionError(AbstractError.INVALID_REQUEST);
			return false;
		}
		
		try {
			//TODO Trivial priority: implement a factory for all major classes
			String username = request.getUsername();
			UserManager manager = new UserManager();
			boolean exist = manager.exist(username);
			
			if (exist == true) {
				error = new CredentialsError(CredentialsError.USERNAME_EXISTS);
				return false;
			}
			
			return true;
		} catch (ManagerException e) {
			error = new UserError(AbstractError.DATABASE_ERROR);
			return false;
		}
	}
}